import userApi from '@/api/user';

export default class AuthService {
    async login(email, password) {
        // eslint-disable-next-line no-useless-catch
        try {
            const response = await userApi.login({ email, password });

            // 由于响应拦截器已经处理了错误情况，这里只需处理成功情况
            const userData = response.data;

            // 存储认证信息
            localStorage.setItem('auth-token', userData.token);
            localStorage.setItem(
                'user-info',
                JSON.stringify({
                    id: userData.id,
                    username: userData.username,
                    email: userData.email,
                    nickname: userData.nickname,
                    avatar: userData.avatar
                })
            );

            return userData;
        } catch (error) {
            // 抛出错误，让调用者处理
            throw error;
        }
    }

    async getUserInfo() {
        // eslint-disable-next-line no-useless-catch
        try {
            const response = await userApi.getInfo();
            return response.data;
        } catch (error) {
            throw error;
        }
    }

    async logout() {

        // 无论 API 调用是否成功，都清除本地存储的认证信息
        localStorage.removeItem('auth-token');
        localStorage.removeItem('user-info');

    }

    isAuthenticated() {
        return localStorage.getItem('auth-token') !== null;
    }

    getUser() {
        const userInfo = localStorage.getItem('user-info');
        return userInfo ? JSON.parse(userInfo) : null;
    }
}
